package com.shasselclub.api.weixin;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.shasselclub.api.v1.result.WeiXinUserResult;
import com.shasselclub.api.v1.service.RedisService;
import com.shasselclub.api.weixin.usermanage.OauthUrlResult;
import com.shasselclub.common.constant.ResultModel;
import com.shasselclub.common.constant.ResultStatus;
import com.shasselclub.common.utils.DateUtil;
import com.shasselclub.common.utils.IpUtils;
import com.shasselclub.common.utils.StringUtils;
import com.shasselclub.common.utils.TokenUtil;
import com.shasselclub.common.utils.map.GetParamToMap;
import com.shasselclub.common.utils.uuid.IdUtils;
import com.shasselclub.project.ask.weixinUser.domain.WeixinUser;
import com.shasselclub.project.ask.weixinUser.service.IWeixinUserService;
import com.sun.jndi.toolkit.url.UrlUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuangxl
 * @description
 * @since 2021-03-04 11:13
 */
@Slf4j
@Controller
@RequestMapping("/api/authorization")
public class WebpageAuthorizationController {
    @Autowired
    private IWeixinUserService weixinUserService;
    @Autowired
    private RedisService redisService;
    /**
     * @description: 静默网页授权，获取openid
     * @author: zhuangxl
     * @since: 21/3/4 12:58
     * @param code: 
     * @param state: 
     * @return: java.lang.String
     **/
    @RequestMapping("/snsapi_base")
    public WxWebPageAccessToken snsapi_base(@RequestParam("code")String code, @RequestParam("state")String state){

        WxWebPageAccessToken wxWebPageAccessToken = new WxWebPageAccessToken();

        try {
            wxWebPageAccessToken = WechatUtil.getAccessTokenAndOpenid(code);
            System.out.println(wxWebPageAccessToken.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return wxWebPageAccessToken;
    }

    /**
     * @description: 手动网页授权，获取用户的基本信息
     * @author: zhuangxl
     * @since: 21/3/4 12:58
     * @param code: 
     * @param state: 
     * @return: java.lang.String
     **/
    @RequestMapping("/snsapi_userinfo")
    public void snsapi_userinfo(@RequestParam("code")String code, @RequestParam("state")String state, HttpServletRequest request,HttpServletResponse response){
        WxWebPageUserinfo wxWebPageUserinfo = new WxWebPageUserinfo();
        ResultModel resultModel=new ResultModel();
        String token="";
        String domain="";
        try {
            Map<String, Object> parameterMap= GetParamToMap.getParameterMap(request);
            Map<String, Object> jsonMap= GetParamToMap.getJosnParameterMap(request);
            domain=request.getServerName();
            log.info("获取服务器域名：{}",domain);
            String path=state;
            log.info("path2:{}", path);
            log.info("state:{}", state);
            log.info("传递过来的参数==="+ JSON.toJSONString(parameterMap)+"ip==="+ IpUtils.getIpAddr(request));
            log.info("传递过来的jsonMap参数==="+ JSON.toJSONString(jsonMap)+"ip==="+ IpUtils.getIpAddr(request));
            WxWebPageAccessToken wxWebPageAccessToken = WechatUtil.getAccessTokenAndOpenid(code);
            wxWebPageUserinfo = WechatUtil.getUserinfo(wxWebPageAccessToken.getAccess_token(), wxWebPageAccessToken.getOpenid());
            log.info("获取到的微信基本信息1", JSON.toJSONString(wxWebPageUserinfo));
            Map<String,Object> queryMap=new HashMap<>();
            queryMap.put("openId",wxWebPageUserinfo.getOpenid());
            int count=weixinUserService.count(queryMap);
            log.info("根据openId查询到的总条数：{}",count);
            WeixinUser weixinUser=new WeixinUser();
            weixinUser.setOpenId(wxWebPageUserinfo.getOpenid());
            weixinUser.setNickName(wxWebPageUserinfo.getNickname());
            weixinUser.setHeadImgUrl(wxWebPageUserinfo.getHeadimgurl());
            weixinUser.setProvince(wxWebPageUserinfo.getProvince());
            weixinUser.setCountry(wxWebPageUserinfo.getCountry());
            weixinUser.setCity(wxWebPageUserinfo.getCity());
            weixinUser.setSex(wxWebPageUserinfo.getSex()+"");
            if(count==0){
                //新增微信用户信息
                log.info("新增微信基本信息参数：{}",JSON.toJSONString(weixinUser));
                weixinUser.setCreateTime(DateUtil.getDateNow());
                int addCount=weixinUserService.insertWeixinUser(weixinUser);
                log.info("新增微信基本信息返回结果：{}",addCount);
            }else{
                WeixinUser updateWeiXinUser=new WeixinUser();
                updateWeiXinUser.setUpdateTime(DateUtil.getDateNow());
                updateWeiXinUser.setOpenId(wxWebPageUserinfo.getOpenid());
                weixinUserService.updateWeixinUser(updateWeiXinUser);
            }
            WeiXinUserResult weiXinUserResult = WeiXinUserResult.boToResult(wxWebPageUserinfo);
            String openId=weixinUser.getOpenId();
            String dateNow= DateUtil.getDateNow();
            String id= IdUtils.fastUUID();
            token=TokenUtil.getInstance().getToken(openId,dateNow,id);
            log.info("生成token：{}",token);
            long time=30l;
            redisService.set(token, weiXinUserResult,time, TimeUnit.DAYS);
            resultModel.setData(weiXinUserResult);
            resultModel.setCode(ResultStatus.SUCCESS.getCode());
            resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
            //将acId作为token保存，存放微信登录后的信息
            if(StringUtils.isEmpty(path)){
                path="http://"+domain;
            }
            String redirectURL=path;
            if(redirectURL.contains("?")){
                redirectURL=redirectURL+"&acId="+token;
            }else{
                redirectURL=redirectURL+"?acId="+token;
            }

            log.info("授权登录之后，跳转的地址为：{}",redirectURL);
            response.sendRedirect(redirectURL);
        } catch (Exception e) {
            e.printStackTrace();
        }

       // return "redirect:" + redirectURL+"?acId="+token;
    }

    @GetMapping("/test")
    @ApiOperation(value = "静默授权获取用户信息",notes = "静默授权获取用户信息",position =3 )
    public OauthUrlResult test(){

        OauthUrlResult oauthUrlResult = new OauthUrlResult();
        try {
            // 静默授权获取用户的openid
            String redirect_uri = "https://admin.fandaren.cn/docs/webpage/authorization/snsapi_base";
            String scope = "snsapi_base";
            //额外参数
            String state = "123";

            String snsapi_base_url = WechatUtil.getWebPageAuthorizationUrl(redirect_uri, scope, state);
            oauthUrlResult.setOpenIdUrl(snsapi_base_url);
            log.info(snsapi_base_url);

            // 手动授权获取用户的基本信息
            redirect_uri = "https://admin.fandaren.cn/docs/webpage/authorization/snsapi_userinfo";
            scope = "snsapi_userinfo";
            //额外参数
            state = "456";

            String snsapi_userinfo_url = WechatUtil.getWebPageAuthorizationUrl(redirect_uri, scope, state);
            log.info(snsapi_userinfo_url);
            oauthUrlResult.setUserInfoUrl(snsapi_userinfo_url);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return oauthUrlResult;
    }

}
